<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="标题: " prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程实例ID: " prop="instanceId">
        <el-input
          v-model="queryParams.instanceId"
          placeholder="请输入流程实例ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button round icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" round icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" min-width="8%" />
      <el-table-column label="请假类型" align="center" prop="type" min-width="8%" />
      <el-table-column label="标题" align="center" prop="title" min-width="8%" />
      <el-table-column label="原因" align="center" prop="reason" min-width="8%" />
      <el-table-column label="开始时间" align="center" min-width="11%">
        <template slot-scope="scope">
          <span>{{ moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" min-width="11%">
        <template slot-scope="scope">
          <span>{{ moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假时长" align="center" min-width="20%">
        <template slot-scope="scope">
          <span>{{ formatTotalDateSub(scope.row.totalTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程实例ID" align="center" prop="instanceId" min-width="13%" />
      <el-table-column label="申请人" align="center" prop="applyUser" min-width="10%">
        <template slot-scope="scope">
          <span style="color: red">{{ scope.row.applyUser }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" min-width="11%">
        <template slot-scope="scope">
          <span>{{ moment(scope.row.applyTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前任务名称" align="center" min-width="15%">
        <template slot-scope="scope">
          <span style="color:#F00; font-weight:bold">{{ scope.row.taskName }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="60%"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.instanceId">
            <el-button
              size="small"
              type="primary"
              round
              icon="el-icon-edit-outline"
              @click="handleFormData(scope.row)"
            >表单数据</el-button>
            <el-button
              size="small"
              type="info"
              round
              icon="el-icon-document"
              @click="handleHistory(scope.row)"
            >审批历史</el-button>
            <el-button
              size="small"
              type="success"
              round
              icon="el-icon-info"
              @click="handleReadresource(scope.row)"
            >进度查看</el-button>
            <el-button
              v-if="scope.row.taskName.indexOf('已结束')=== -1"
              size="small"
              type="warning"
              round
              icon="el-icon-circle-close"
              @click="handleUndo(scope.row)"
            >撤销</el-button>
            <el-button
              v-if="scope.row.taskName.indexOf('已结束')=== -1"
              size="small"
              type="danger"
              round
              icon="el-icon-news"
              @click="handleSuspend(scope.row)"
            >{{ scope.row.suspendState === '2' ? '激活' : '挂起' }}</el-button>
          </div>
          <div v-else>
            <el-button
              size="small"
              round
              type="primary"
              icon="el-icon-user"
              @click="handleSubmitApply(scope.row)"
            >提交申请</el-button>
            <el-button
              size="small"
              type="info"
              round
              icon="el-icon-edit"
              @click="handleEditForm(scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              round
              icon="el-icon-delete"
              @click="handleRemoveForm(scope.row)"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加请假业务对话框 -->
    <el-dialog
      :title="dialogParams.addTitle"
      :visible.sync="dialogParams.addOpen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="标题: ">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="原因: ">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="开始时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.startTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.endTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假时长: ">
          <el-input v-model="addViewTotalTime" placeholder="请假时长" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogParams.addOpen=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑请假业务对话框 -->
    <el-dialog
      :title="dialogParams.editTitle"
      :visible.sync="dialogParams.editOpen"
      width="600px"
      append-to-body
    >
      <el-form ref="editForm" :model="leaveForm" :rules="rules" label-width="90px">
        <el-form-item label="标题: ">
          <el-input v-model="leaveForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="原因: ">
          <el-input v-model="leaveForm.reason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="开始时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="leaveForm.startTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="leaveForm.endTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假时长: ">
          <el-input v-model="leaveForm.totalTime" placeholder />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm(leaveForm)">确 定</el-button>
        <el-button @click="dialogParams.editOpen=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批历史对话框  -->
    <el-dialog
      :visible.sync="dialogParams.historyOpen"
      :title="dialogParams.historyTitle"
      width="900px"
      append-to-body
    >
      <el-form :model="historyQueryParams" ref="queryForm" :inline="true">
        <el-form-item label="任务名称: " prop="activityName">
          <el-input
            v-model="historyQueryParams.activityName"
            placeholder="请输入任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="办理人ID: " prop="assignee">
          <el-input
            v-model="historyQueryParams.assignee"
            placeholder="请输入办理人ID"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="historyLoading" :data="historyList">
        <el-table-column label="任务名称" align="center" prop="activityName" min-width="12%" />
        <el-table-column label="办理人" align="center" prop="assigneeName" min-width="12%" />
        <el-table-column label="审批意见" align="center" prop="comment" min-width="12%" />
        <el-table-column label="开始时间" align="center" prop="startTime" min-width="15%">
          <template slot-scope="scope">
            <span>{{ moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" min-width="15%">
          <template slot-scope="scope">
            <span>{{ moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="耗时" align="center" prop="durationInMillis" min-width="15%">
          <template slot-scope="scope">
            <span>{{ formatTotalDateSub(scope.row.durationInMillis/1000) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="historyListTotal>0"
        :total="historyListTotal"
        :page.sync="historyQueryParams.pageNum"
        :limit.sync="historyQueryParams.pageSize"
        @pagination="getHistoryList"
      />
    </el-dialog>

    <!-- 查看进度弹出层 -->
    <el-dialog
      :visible.sync="dialogParams.readResourceOpen"
      :title="dialogParams.readResourceTitle"
      width="800px"
      append-to-body
    >
      <div>
        <el-image src=""></el-image>
      </div>
    </el-dialog>

    <!-- 表单数据弹出层 -->
    <el-dialog
      :visible.sync="dialogParams.fdOpen"
      :title="dialogParams.fdTitle"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="formData" label-width="90px">
        <el-form-item label="申请人：">
          <el-input v-model="formData.applyUserName" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="formData.title" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="原因：">
          <el-input v-model="formData.reason" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="开始时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="formData.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="formData.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假时长: ">
          <el-input v-model="viewTotalTime.formDataTotalTime" placeholder :readonly="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogParams.fdOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLeave,
  addLeave,
  removeLeave,
  editLeave,
  submitApplyLeave,
  suspendOrActiveApply,
  cancelApply
} from "@/api/process/leave/leave";
import { listHistory, readresourceLeave } from "@/api/process/processMenu/definition";
import moment from "moment";
export default {
  name: "Leave",
  data() {
    return {
      src: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 请假表格数据
      leaveList: [],
      // 审批历史表格数据
      historyList: [],
      historyLoading: true,
      historyListTotal: 0,
      // 表单数据
      formData: {
        totalTime: undefined
      },
      // 编辑表单数据
      leaveForm: {},
      historyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: undefined,
        assign: undefined
      },
      // 显示作用的totalTIme
      viewTotalTime: {
        formDataTotalTime: undefined,
        addTotalTime: undefined
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        reason: undefined,
        startTime: undefined,
        endTime: undefined,
        totalTime: undefined
      },
      // 弹出层参数
      dialogParams: {
        // 增加弹出层
        addOpen: false,
        addTitle: "",

        // 历史审批弹出层
        historyOpen: false,
        historyTitle: "",

        // 高亮图弹出层
        readResourceOpen: false,
        readResourceTitle: "",

        // 表单数据弹出层
        fdOpen: false,
        fdTitle: "",

        // 编辑弹出层
        editOpen: false,
        editTitle: "",
        totalTime: this.totalTime
      },
      // 表单参数
      form: {
        startTime: undefined,
        endTime: undefined
      },
      editForm: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        reason: [
          { required: true, message: "请假原因不能为空", trigger: "blur" }
        ],
        startTime: [{ required: true, message: "必填", trigger: "blur" }],
        endTime: [{ required: true, message: "必填", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },

  computed: {
    totalTime: function() {
      return this.calcTotalSecond(this.form.startTime, this.form.endTime);
    },

    addViewTotalTime: function() {
      return this.formatTotalDateSub(this.totalTime);
    }
  },

  methods: {
    // 计算时间差,单位: 秒
    calcTotalSecond(startDateStr, endDateStr) {
      var date1 = new Date(startDateStr); // 开始时间
      var date2 = new Date(endDateStr); // 结束时间
      var timeSub = date2.getTime() - date1.getTime(); // 时间差毫秒
      return timeSub / 1000;
    },

    // 计算时间差，单位: xx天xx时xx分xx秒
    formatTotalDateSub(row, column) {
      let secondSub = row;
      var days = Math.floor(secondSub / (24 * 3600)); // 计算出小时数
      var leave1 = secondSub % (24 * 3600); // 计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / 3600); // 计算相差分钟数
      var leave2 = leave1 % 3600; // 计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / 60); // 计算相差秒数
      var leave3 = leave2 % 60; // 计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3);
      return (
        days + " 天 " + hours + " 时 " + minutes + " 分 " + seconds + " 秒"
      );
    },

    /** 查询请假列表 */
    getList() {
      this.loading = true;
      listLeave(this.queryParams).then(response => {
        this.leaveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询历史审核列表 */
    getHistoryList(row) {
      this.historyLoading = true;
      var params = new URLSearchParams();
      params.append("instanceId", row.instanceId);
      listHistory(params)
        .then(response => {
          this.historyList = response.rows;
          this.historyListTotal = response.total;
          this.historyLoading = false;
        })
        .catch(function() {});
    },

    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        reason: undefined,
        startTime: undefined,
        endTime: undefined,
        totalTime: undefined
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.dialogParams.addOpen = true;
      this.dialogParams.addTitle = "添加请假业务";
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.totalTime = this.totalTime;
          let params = this.form;
          return addLeave(params)
            .then(() => {
              this.dialogParams.addOpen = false;
              this.getList();
              this.msgSuccess("操作成功");
            })
            .catch(function() {});
        }
      });
    },

    /** 编辑提交按钮 */
    submitEditForm: function(row) {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          var params = new URLSearchParams();
          params.append("id", row.id);
          return editLeave(params)
            .then(() => {
              this.dialogParams.editOpen = false;
              this.getList();
              this.msgSuccess("操作成功");
            })
            .catch(function() {});
        }
      });
    },

    /** 历史审批按钮操作 */
    handleHistory(row) {
      this.dialogParams.historyOpen = true;
      this.dialogParams.historyTitle = "查看历史审批";
      this.getHistoryList(row);
    },

    /** 进度查看按钮操作 */
    handleReadresource(row) {
      var params = new URLSearchParams();
      params.append("pProcessInstanceId", row.instanceId);
      return readresourceLeave(params)
        .then(() => {
          this.dialogParams.readResourceOpen = true;
          this.dialogParams.readResourceTitle = "查看流程图";
          this.src = readresourceLeave+'?'+'pProcessInstanceId='+row.instanceId;
        })
        .catch(function() {});
    },

    /** 撤销按钮操作 */
    handleUndo(row) {
      var params = new URLSearchParams();
      var applyState = row.suspendState === "2" ? "激活" : "挂起";
      params.append("instanceId", row.instanceId);
      this.$confirm("确定要撤销申请吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return cancelApply(params);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
        .catch(function() {});
    },

    /** 激活挂起按钮操作 */
    handleSuspend(row) {
      var params = new URLSearchParams();
      var applyState = row.suspendState === "2" ? "激活" : "挂起";
      params.append("instanceId", row.instanceId);
      params.append("suspendState", row.suspendState);
      this.$confirm("确定要" + applyState + "申请吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return suspendOrActiveApply(params);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
        .catch(function() {});
    },

    /** 删除按钮操作 */
    handleRemoveForm(row) {
      var params = new URLSearchParams();
      params.append("ids", row.id);
      return removeLeave(params)
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 提交申请按钮操作 */
    handleSubmitApply(row) {
      var params = new URLSearchParams();
      params.append("id", row.id);
      this.$confirm("确认要提交申请吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return submitApplyLeave(params);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("提交申请成功");
        })
        .catch(function() {});
    },
    /**表单数据按钮操作 */
    handleFormData(row) {
      this.viewTotalTime.formDataTotalTime = this.formatTotalDateSub(
        row.totalTime
      );
      this.formData = row;
      this.dialogParams.fdOpen = true;
      this.dialogParams.fdTitle = "业务详情";
    },
    /** 编辑按钮操作 */
    handleEditForm(row) {
      this.leaveForm = row;
      this.dialogParams.editOpen = true;
      this.dialogParams.editTitle = "修改请假业务";
    }
  }
};
</script>